package com.zhengdongzulin.zuke.app.main.mine.lifeservice

import android.app.Dialog
import android.content.Intent
import android.view.View
import android.widget.TextView
import androidx.lifecycle.Observer
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.lxj.androidktx.core.*
import com.lxj.androidktx.livedata.StateLiveData
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.zhengdongzulin.zuke.R
import com.zhengdongzulin.zuke.app.data.LifeService
import com.zhengdongzulin.zuke.base.BaseFragment
import com.zhengdongzulin.zuke.databinding.DialogLifeServiceAppraiseBinding
import com.zhengdongzulin.zuke.databinding.ZkFragmentLifeServiceBinding
import com.zhengdongzulin.zuke.ext.callPhoneDialog
import com.zhengdongzulin.zuke.ext.getBottomDialog
import com.zhengdongzulin.zuke.ext.put
import com.zhengdongzulin.zuke.ext.start
import com.zhengdongzulin.zuke.parser.ObjectList

class ZKLifeServiceFragment(var mStatusType: LifeServiceType) :
    BaseFragment<LifeServiceVm, ZkFragmentLifeServiceBinding>() {

    enum class LifeServiceType {
        ALL,    //全部
        IN_PROCESS, //处理中
        TO_BE_EVALUATED //待评价
    }

    lateinit var mType: String
    private var mData: MutableList<LifeService> = mutableListOf()
    lateinit var mAdapter: VListAdpater
    private var mPositionCancel = -1
    lateinit var mDialog: Dialog

    companion object {
        fun newInstance(type: LifeServiceType) = ZKLifeServiceFragment(type)
    }

    override fun getLayoutResId(): Int = R.layout.zk_fragment_life_service

    override fun initVM(): LifeServiceVm = getVM(LifeServiceVm::class.java)

    override fun initView() {
        mType = (activity as ZKLifeServiceActivity).mType.toString()
        mView.statusView.showLoading()
        initAdapter()
    }

    override fun initData() {
        getData()
    }

    override fun initListener() {

    }

    private fun initAdapter() {
        mAdapter = VListAdpater(mData)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            Intent()
                .put("id", mData[position].id)
                .put("type", mType)
                .start(requireActivity(), ZKLifeServiceDetailsActivity::class.java)
        }
        mView.recyclerView.vertical().adapter = mAdapter
        mView.statusView.setOnRetryClickListener {
            if (it.id == R.id.empty_view) {
                getData()
            }
        }
        mView.contentView.setEnableRefresh(true)
        mView.contentView.setOnRefreshListener {
            mView.contentView.resetNoMoreData()
            mViewModel.mCurrentPage = 1
            getData()
        }
        mView.contentView.setOnLoadMoreListener {
            mViewModel.mCurrentPage++
            if (mViewModel.mCurrentPage > mViewModel.mPageTotal) {
                mView.contentView.finishLoadMoreWithNoMoreData()
                toast("没有更多数据了")
            } else {
                getData()
            }
        }
    }

    private fun getData() {
        mView.statusView.showLoading()
        when (mType) {
            "保洁" -> {
                mViewModel.clean_list((activity as ZKLifeServiceActivity).mHouseId, getStatus())
            }
            "维修" -> {
                mViewModel.repair_list((activity as ZKLifeServiceActivity).mHouseId, getStatus())
            }
            "投诉" -> {
                mViewModel.complaint_letter_list(
                    (activity as ZKLifeServiceActivity).mHouseId,
                    getStatus()
                )
            }
        }
    }

    override fun startObserve() {
        mViewModel.clean_list.observe(this, androidx.lifecycle.Observer {
            processingData(it)
        })
        mViewModel.clean_list.state.observe(this, Observer {
            processingDataError(it, mViewModel.clean_list.errMsg!!)
        })

        mViewModel.repair_list.observe(this, androidx.lifecycle.Observer {
            processingData(it)
        })
        mViewModel.repair_list.state.observe(this, Observer {
            processingDataError(it, mViewModel.repair_list.errMsg!!)
        })

        mViewModel.complaint_letter_list.observe(this, androidx.lifecycle.Observer {
            processingData(it)
        })
        mViewModel.complaint_letter_list.state.observe(this, Observer {
            processingDataError(it, mViewModel.complaint_letter_list.errMsg!!)
        })

        mViewModel.clean_cancel.observe(this, androidx.lifecycle.Observer {
            cancelSuccess()
        })
        mViewModel.clean_cancel.state.observe(this, Observer {
            processingOperationError(it, mViewModel.clean_cancel.errMsg!!)
        })

        mViewModel.repair_cancel.observe(this, androidx.lifecycle.Observer {
            cancelSuccess()
        })
        mViewModel.repair_cancel.state.observe(this, Observer {
            processingOperationError(it, mViewModel.repair_cancel.errMsg!!)
        })

        mViewModel.complaint_letter_cancel.observe(this, androidx.lifecycle.Observer {
            cancelSuccess()
        })
        mViewModel.complaint_letter_cancel.state.observe(this, Observer {
            processingOperationError(it, mViewModel.complaint_letter_cancel.errMsg!!)
        })

        mViewModel.clean_appraise.observe(this, androidx.lifecycle.Observer {
            appraiseSuccess()
        })
        mViewModel.clean_appraise.state.observe(this, Observer {
            processingOperationError(it, mViewModel.clean_appraise.errMsg!!)
        })

        mViewModel.repair_appraise.observe(this, androidx.lifecycle.Observer {
            appraiseSuccess()
        })
        mViewModel.repair_appraise.state.observe(this, Observer {
            processingOperationError(it, mViewModel.repair_appraise.errMsg!!)
        })

        mViewModel.complaint_letter_appraise.observe(this, androidx.lifecycle.Observer {
            appraiseSuccess()
        })
        mViewModel.complaint_letter_appraise.state.observe(this, Observer {
            processingOperationError(it, mViewModel.complaint_letter_appraise.errMsg!!)
        })
    }

    /**
     * 处理数据
     */
    private fun processingData(it: ObjectList<LifeService>) {
        mViewModel.mPageTotal = it.pages
        if (mViewModel.mCurrentPage == 1) {
            mData.clear()
            mView.contentView.finishRefresh()
        }
        mData.addAll(it.records)
        if (mData.size == 0) {
            mView.statusView.showEmpty()
        } else {
            mView.statusView.showContent()
        }
        mAdapter.notifyDataSetChanged()
        mView.contentView.finishLoadMore()
    }

    /**
     * 处理数据 error
     */
    private fun processingDataError(it: StateLiveData.State, errorMsg: String) {
        when (it) {
            StateLiveData.State.Empty -> {
                mView.statusView.showEmpty()
            }
            StateLiveData.State.Error -> {
                toast(errorMsg)
                mView.statusView.showEmpty()
            }
        }
    }

    /**
     * 处理操作 error
     */
    private fun processingOperationError(it: StateLiveData.State, errorMsg: String) {
        when (it) {
            StateLiveData.State.Error -> {
                toast(errorMsg)
                mPositionCancel = -1
            }
        }
    }

    /**
     * 获取保洁 status
     * 保洁  维修  投诉  的status都是
     * 1待处理 2已派单 3待验收 4 已取消 5 已验收（已完成）
     */
    private fun getStatus(): String {
        return when (mStatusType) {
            LifeServiceType.ALL -> {
                ""
            }
            LifeServiceType.IN_PROCESS -> {
                "1,2"
            }    //处理中
            LifeServiceType.TO_BE_EVALUATED -> {
                "5"
            }   //待评价
        }
        return ""
    }

    /**
     * 获取status对应的中文
     * 1待处理 2已派单 3待验收 4 已取消 5 已验收（已完成）
     */
    private fun getStatusStr(status: String): String {
        when (status) {
            "1" -> {
                return "处理中"
            }
            "2" -> {
                return "已派单"
            }
            "3" -> {
                return "待验收"
            }
            "4" -> {
                return "已取消"
            }
            "5" -> {
                return "已验收"
            }
        }
        return status
    }

    inner class VListAdpater(
        list: MutableList<LifeService>
    ) : BaseQuickAdapter<LifeService, BaseViewHolder>(
        R.layout.item_life_service,
        list
    ) {
        override fun convert(holder: BaseViewHolder, item: LifeService) {
            holder.setText(R.id.tv_file_status, getStatusStr(item.status))

            when (mType) {
                "保洁" -> {
                    holder.setText(R.id.tv_file_time, "预约上门时间：${item.expectCompletionTime}")
                }
                "维修" -> {
                    holder.setText(R.id.tv_file_time, "预约上门时间：${item.expectCompletionTime}")
                }
                "投诉" -> {
                    holder.setText(R.id.tv_file_time, "提交时间：${item.expectCompletionTime}")
                }
            }
            holder.setText(R.id.tv_life_address, "服务地点：${item.houseAddress}")

            holder.getView<TextView>(R.id.tv_life_btn1).visibility = View.VISIBLE
            holder.setText(R.id.tv_life_btn2, "联系管家")
            when (item.status) {
                "1", "2" -> {    //取消订单
                    holder.setText(R.id.tv_life_btn1, "取消订单")
                }
                "5" -> {  //已完成
                    when (item.appraise) {
                        "1" -> {
                            holder.setText(R.id.tv_life_btn1, "已评价")
                            holder.getView<TextView>(R.id.tv_life_btn1).visibility = View.GONE
                        }
                        else -> {
                            holder.setText(R.id.tv_life_btn1, "评价")
                            holder.getView<TextView>(R.id.tv_life_btn1).visibility = View.VISIBLE
                        }
                    }
                }
                else -> {  //隐藏
                    holder.getView<TextView>(R.id.tv_life_btn1).visibility = View.GONE
                }
            }
            holder.getView<TextView>(R.id.tv_life_btn1).setOnClickListener {
                when (item.status) {
                    "1", "2" -> {    //取消订单
                        cancel(item.id, holder.absoluteAdapterPosition)
                    }
                    "5" -> {  //评价
                        appraise(item.id, holder.absoluteAdapterPosition)
                    }
                }
            }
            holder.getView<TextView>(R.id.tv_life_btn2).setOnClickListener {
                //联系管家
                requireActivity().callPhoneDialog(item.housekeeperName, item.housekeeperPhone)
                    .show()
            }
        }
    }

    /**
     * 取消订单
     */
    fun cancel(id: String, position: Int) {
        MaterialDialog.Builder(requireActivity())
            .content("确定要取消" + mType + "服务吗？")
            .positiveText("确定")
            .negativeText("取消")
            .contentColor(color(R.color.black_66))
            .negativeColor(color(R.color.gray_99))
            .positiveColor(color(R.color.color_1273f7))
            .onPositive { dialog, which ->
                mPositionCancel = position
                when (mType) {
                    "保洁" -> {
                        mViewModel.clean_cancel(id)
                    }
                    "维修" -> {
                        mViewModel.repair_cancel(id)
                    }
                    "投诉" -> {
                        mViewModel.complaint_letter_cancel(id)
                    }
                }
                dialog.dismiss()
            }.show()

    }

    /**
     * 取消成功
     */
    private fun cancelSuccess() {
        toast("取消成功")
        mData[mPositionCancel].status = "4" //设置为已取消
        mAdapter.notifyItemChanged(mPositionCancel)
        mPositionCancel = -1
    }


    /**
     * 评价订单
     */
    fun appraise(id: String, position: Int) {
        var view = DialogLifeServiceAppraiseBinding.inflate(layoutInflater)
        mDialog = requireActivity().getBottomDialog(view.root, 0.0)
        view.ivClose.setOnClickListener {
            mDialog.dismiss()
        }
        var ratingBar = view.ratingBar
        view.ok.setOnClickListener {
            var grade = ratingBar.rating

            var gradeContent = view.etAppraiseInput.text.trim().toString()
            if (grade == 0.0f) {
                toast("请选择评分")
                return@setOnClickListener
            }
            if (gradeContent.isNullOrEmpty()) {
                toast("请输入服务内容")
                return@setOnClickListener
            }


            mPositionCancel = position
            when (mType) {
                "保洁" -> {
                    mViewModel.clean_appraise(id, grade.toInt().toString(), gradeContent)
                }
                "维修" -> {
                    mViewModel.repair_appraise(id, grade.toInt().toString(), gradeContent)
                }
                "投诉" -> {
                    mViewModel.complaint_letter_appraise(id, grade.toInt().toString(), gradeContent)
                }
            }

        }
        mDialog.show()

    }

    /**
     * 评价成功
     */
    private fun appraiseSuccess() {
        toast("评价成功")
        mDialog.dismiss()
        mData[mPositionCancel].appraise = "1" //设置为已评价
        mAdapter.notifyItemChanged(mPositionCancel)
        mPositionCancel = -1
    }


}